package com.xiaobai.java_core.objcopy;

import java.lang.reflect.Field;

/**
 * @author wangtw
 * @ClassName CopyUtils
 * @description: 拷贝工具类
 * @date 2024/10/719:54
 */
public class CopyUtils {

    /**
     * 浅拷贝
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> T simpleCopy(T obj) {

        Class<?> TClass = obj.getClass();

        T copyObj = null;
        try {
            copyObj  = (T) TClass.newInstance();
            Field[] declaredFields = TClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                Object val = declaredField.get(obj);
                if (val != null) {
                    declaredField.set(copyObj, val);
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return copyObj;

    }

}
